package com.base.sweb;

import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.base.commonlib.base.CBaseMvpFragment;
import com.base.sweb.client.ChromeClientCallbackManager;
import com.base.sweb.client.DefaultWebClient;
import com.base.sweb.client.MiddleWareWebChromeBase;
import com.base.sweb.client.MiddleWareWebClientBase;
import com.base.sweb.client.WebDefaultSettingsManager;
import com.base.sweb.client.WebSettings;
import com.base.sweb.databinding.FragmentSuperwebx5fullBinding;
import com.base.sweb.file.DownLoadResultListener;
import com.base.sweb.manage.IWebLayout;
import com.base.sweb.manage.SuperWebX5;
import com.base.sweb.progress.BaseIndicatorView;
import com.base.sweb.utils.PermissionInterceptor;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;

/**
 * Created by weikailiang on 2020/3/13.
 */

public class SuperWebX5FullFragment extends CBaseMvpFragment{
    private FragmentSuperwebx5fullBinding mBinding;
    protected SuperWebX5 mSuperWebX5;
    private MiddleWareWebChromeBase mMiddleWareWebChrome;
    private MiddleWareWebClientBase mMiddleWareWebClient;
    @Override
    public void init() {
        mBinding = (FragmentSuperwebx5fullBinding) mRootBinding;
        mSuperWebX5 = SuperWebX5.with(this)
                .setSuperWebParent((LinearLayout)mBinding.getRoot(), new LinearLayout.LayoutParams(-1, -1))
                .setCustomIndicator(getIndicatorView())
                .setWebLayout(getWebLayout())
                .setWebSettings(getSettings())
                .setWebViewClient(mWebViewClient)
                .setWebChromeClient(mWebChromeClient)
                .setReceivedTitleCallback(mCallback)
                .setPermissionInterceptor(mPermissionInterceptor)
                .setNotifyIcon(R.mipmap.download)
                .useMiddleWareWebChrome(getMiddleWareWebChrome())
                .useMiddleWareWebClient(getMiddleWareWebClient())
                .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)
                .interceptUnkownScheme()
                .openParallelDownload()
                .setSecurityType(SuperWebX5.SecurityType.strict)
                .addDownLoadResultListener(mDownLoadResultListener)
                .createSuperWeb()
                .ready()
                .go(getUrl());
    }

    @Override
    public void start() {

    }
    public MiddleWareWebChromeBase getMiddleWareWebChrome() {
        return mMiddleWareWebChrome;
    }

    public MiddleWareWebClientBase getMiddleWareWebClient() {
        return mMiddleWareWebClient;
    }

    /**
     * 权限拦截器
     * 在触发某些敏感的 Action 时候会回调该方法， 比如定位触发 。
     * 例如 https//:www.baidu.com 该 Url 需要定位权限， 返回false ，如果版本大于等于23 ， 会动态申请权限 ，true 该Url对应页面请求定位失败。
     * 该方法是每次都会优先触发的 ， 开发者可以做一些敏感权限拦截
     */
    protected PermissionInterceptor mPermissionInterceptor = new PermissionInterceptor() {

        @Override
        public boolean intercept(String url, String[] permissions, String action) {
            return false;
        }
    };

    /**
     * 文件下载结果监听
     */
    protected DownLoadResultListener mDownLoadResultListener = new DownLoadResultListener() {
        @Override
        public void success(String path) {
            Toast.makeText(getContext(),"下载成功,存储地址:"+path, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void error(String path, String resUrl, String cause, Throwable e) {
            Toast.makeText(getContext(),"下载失败", Toast.LENGTH_SHORT).show();
        }
    };


    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_superwebx5full;
    }
    protected IWebLayout getWebLayout() {
        return null;
    }

    protected BaseIndicatorView getIndicatorView(){
        return null;
    }
    /**
     * 获取WebView设置
     */
    public WebSettings getSettings() {
        return WebDefaultSettingsManager.getInstance();
    }

    /**
     * 获取url
     */
    public String getUrl() {
        String target = "https://www.baidu.com";
        return target;
    }
    /**
     * 获取进度条
     */
    protected WebChromeClient mWebChromeClient = new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }
    };

    /**
     * 获取网页title
     */
    protected ChromeClientCallbackManager.ReceivedTitleCallback mCallback = new ChromeClientCallbackManager.ReceivedTitleCallback() {
        @Override
        public void onReceivedTitle(WebView view, String title) {

        }
    };



    /**
     * 采用X5客户端拦截URL
     */
    protected com.tencent.smtt.sdk.WebViewClient mWebViewClient = new com.tencent.smtt.sdk.WebViewClient() {

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }


        @Override
        public boolean shouldOverrideUrlLoading(final WebView view, String url) {
            //intent:// scheme的处理 如果返回false ， 则交给 DefaultWebClient 处理 ， 默认会打开该Activity  ， 如果Activity不存在则跳到应用市场上去.  true 表示拦截
            //例如优酷视频播放 ，intent://play?vid=XODEzMjU1MTI4&refer=&tuid=&ua=Mozilla%2F5.0%20(Linux%3B%20Android%207.0%3B%20SM-G9300%20Build%2FNRD90M%3B%20wv)%20AppleWebKit%2F537.36%20(KHTML%2C%20like%20Gecko)%20Version%2F4.0%20Chrome%2F58.0.3029.83%20Mobile%20Safari%2F537.36&source=exclusive-pageload&cookieid=14971464739049EJXvh|Z6i1re#Intent;scheme=youku;package=com.youku.phone;end;
            //优酷想唤起自己应用播放该视频 ， 下面拦截地址返回 true  则会在应用内 H5 播放 ，禁止优酷唤起播放该视频， 如果返回 false ， DefaultWebClient  会根据intent 协议处理 该地址 ， 首先匹配该应用存不存在 ，如果存在 ， 唤起该应用播放 ， 如果不存在 ， 则跳到应用市场下载该应用 .
            if (url.startsWith("intent://")) {
                return true;
            } else if (url.startsWith("youku")) {
                return true;
            }

            return false;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {


        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }
    };


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("Info", "onActivityResult -- >callback:" + requestCode + "   0x254:" + 0x254);
        mSuperWebX5.uploadFileResult(requestCode, resultCode, data);
    }
}
